<template>
  <div class="tabl-container">
    <el-table :data="paginatedTableData" style="width: 100%; max-height: 65vh;">
      <el-table-column fixed prop="mid" label="药单编号" width="250" />
      <el-table-column label="药品" width="250" >
        <template v-slot="scope">
          <div class="text-ellipsis" v-html="scope.row.drugs.replace(/\n/g, '<br>')"></div>
        </template>
      </el-table-column>
      <el-table-column
        prop="ifTake"
        label="状态"
        width="250"
        fixed="right"
        :filters="[
          { text: '已配好', value: '0' },
          { text: '已取消', value: '-1' },
          { text: '已取药', value: '1' },
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template #default="scope">
          <el-tag
            :type="getTagType(scope.row.ifTake)"
            disable-transitions
            >{{ getStatusText(scope.row.ifTake) }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="250">
        <template #header>
          <el-input v-model="search" placeholder="输入药单编号搜索" />
        </template>
        <template #default="scope">
          <el-button
            type="primary"
            :disabled="scope.row.ifTake !== '0'"
            @click="handleGetMed(scope.$index, scope.row)"
          >
            取药
          </el-button>
          <el-button
            :disabled="scope.row.ifTake === '-1'"
            @click="handleRefund(scope.$index, scope.row)"
          >
            退费
          </el-button>
          <el-button
            type="primary"
            :disabled="scope.row.ifTake !== '0'"
            @click="handleCheck(scope.$index, scope.row)"
          >
            去核查
          </el-button>
        </template>
      </el-table-column>
    </el-table>

  </div>
  <div class="pagination-block">
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="tableData.length"
    />
  </div>
</template>

<script>
import request from "@/utils/request.js";

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      // 原始数据
      // ifTake：-1已取消，0已配好，1已取药
      tableData: [
        // {
        //   mid: '19920929',
        //   drugs: '阿莫西林  11111\n第二行\n第三行\n第四行',
        //   ifTake: '0',
        // },
        // {
        //   mid: '19920929',
        //   drugs: '111',
        //   ifTake: '1',
        // },
        // {
        //   mid: '19920929',
        //   drugs: '222',
        //   ifTake: '-1',
        // },
        // {
        //   mid: 'M63003',
        //   drugs: '阿利芬胶囊 2\n泽力普片 3\n葡萄糖苯甲酸片 2\n氟康唑乳膏 3',
        //   ifTake: '0',
        // },
      ],
      search: "",
    };
  },
  mounted() {
    this.requestDrugQueue();
  },
  computed: {
    filterTableData() {
      return this.tableData.filter(
        (data) => !this.search || data.mid.includes(this.search)
      );
    },
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filterTableData.slice(start, end);
    },
  },
  methods: {
    handleCurrentChange(page) {
      this.currentPage = page;
      console.log("当前页码:", this.currentPage);
    },
    requestDrugQueue(){
      request
        .get("/medicalRecord/getMedicalRecordList")
        .then((res) => {
          console.log('success',res);
          this.tableData = res.data;
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    handleGetMed(index, row) {
      row.ifTake = '1',
      console.log('取药按钮被点击', index, row);
      
      // 执行取药逻辑
      request
      .get('/doctor/updateIfTake1', {
          params: {
            mId: row.mid
          }
        })
        .then((res) => {
          console.log('取药成功',res);
          this.$message.success('取药成功.');
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    getCurrentTime() {
      // 获取当前时间
      let currentTime = new Date();
      
      // 格式化时间
      const year = currentTime.getFullYear();
      const month = String(currentTime.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
      const day = String(currentTime.getDate()).padStart(2, '0');
      const hours = String(currentTime.getHours()).padStart(2, '0');
      const minutes = String(currentTime.getMinutes()).padStart(2, '0');
      const seconds = String(currentTime.getSeconds()).padStart(2, '0');
      
      // 拼接成所需格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 执行退费逻辑
    async handleRefund(index, row) {
      row.ifTake = '-1',
      console.log('退费按钮被点击', index, row);
      try {
        
      await request
      .get('/refundRecord/addRefundRecord', {
          params: {
            time: this.getCurrentTime(),
            mid: row.mid,
            type: "0",
          }
        })
        .then((res) => {
          console.log('退费',res);
          this.$message.success('退费成功.');
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
      } catch (error) {
        console.error("在创建退费单时发生错误:", error);
        this.$message.error('在创建退费单时发生错误.');
      }
    },
    handleCheck(index, row) {
      this.$router.push({ name: "DoctorDrugStock", params: { drugs: row.drugs } });
      console.log('核查按钮被点击', index, row);
      console.log('查看当前时间', index, this.getCurrentTime());
    },
    getTagType(tag) {
      return {
        '1': 'primary',
        '-1': 'info',
        '0': 'success', 
      }[tag] || 'default'; // 如果 tag 不匹配任何已知值，则默认为 'default'
    },
    getStatusText(tag) {
      return {
        '1': '已取药',
        '-1': '已取消',
        '0': '已配好', 
      }[tag] || 'default'; // 如果 tag 不匹配任何已知值，则默认为 'default'
    },
    filterTag(value, row) {
      return row.ifTake === value;
    },
  },
};
</script>

<style scoped>
/* 添加样式 */
.tabl-container {
  height: 65vh;
}
.text-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 限制显示的行数 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  white-space: normal; /* 允许文本换行，但会被 -webkit-line-clamp 限制 */
  line-height: normal; /* 确保行高正常，避免由于固定行高导致的显示问题 */
}
.pagination-block {
  display: flex; /* 使用flexbox布局 */
  justify-content: center; /* 水平居中对齐 */
  margin-top: 20px; /* 添加上边距 */
}
.pagination-block el-pagination {
  justify-content: center;
}
</style>